<template>
    <div>
        <div class="my-richtext" :class="{
            'pl-2 pr-2': props.label,
            'pb-[10px]': props.label && props.mode == 'view',
            'pt-4': props.label && props.mode == 'view'
        }">
            <!-- 標題 -->
            <div :class="{
                'mb-4': props.mode != 'view',
                'mb-1': props.mode == 'view'
            }" class="flex mb-4" v-if="props.label" :style="{ opacity: props.label == '#' ? 0 : 1 }">
                <div class="text-error text-[14px] leading-[14px]"
                    v-if="props.required == true && props.mode != 'view'">*</div>
                <div class="text-text--primary text-[14px] leading-[14px] font-[500]">{{ $t(props.label) }}</div>
            </div>
            <!-- 全屏时组件瞬移到body， 解决层级问题 -->
            <Teleport to="body" :disabled="isFullScreen == false">
                <div class="mrc-ess-rich-text rounded-[10px] overflow-hidden bg-surface" :class="{
                    'border-divider': props.mode != 'view',
                    '!shadow-none': props.mode == 'view'
                }" :style="{
                    zIndex: isFullScreen == true ? 999999 : 0,
                }">
                    <!-- 語言切換 -->
                    <div :class="{
                        'bg-header-bg': true
                    }">
                        <div class="pa-2 flex">
                            <div class="bg-surface rounded-[4px] border-divider overflow-hidden">
                                <v-btn :color="lang.value == currentLang ? 'primary' : ''"
                                    :variant="lang.value == currentLang ? 'tonal' : 'text'"
                                    class="!rounded-[0] border-divider !min-w-[40px]" v-for="lang in langList" :key="lang.value"
                                    @click="changeLang(lang.value)">
                                    <span class="normal-case font-[700] text-[14px] leading-[14px]" :class="{
                                        'text-text--secondary': lang.value != currentLang,
                                    }">{{ lang.label }}</span>
                                </v-btn>
                            </div>
                        </div>
                    </div>
                    <!-- 分割綫 -->
                    <div class="border-bottom-divider" v-if="props.mode != 'view'"></div>
                    <!-- 工具欄 -->
                    <Toolbar class="bg-header-bg" :editor="_editor" :defaultConfig="toolbarConfig"
                        v-show="props.mode != 'view'" />
                    <!-- 編輯器 -->
                    <Editor v-if="showRichTextEditor" v-model="richText[currentLang]" :defaultConfig="editorConfig"
                        @onCreated="handleCreated" style="height: 500px;" />
                </div>
            </Teleport>

            <!-- 新提示 -->
            <mrc_ess_InputBottomTip :tip="props.tip" :tipDetail="props.tipDetail"></mrc_ess_InputBottomTip>
        </div>
        <!-- 分割线 -->
        <v-divider v-if="props.mode == 'view' && props.divider == true"></v-divider>
        <!-- 间距 -->
        <div class="pointer-events-none" v-if="props.mode != 'view' || props.spacing == true" :style="{
            height: props.spacingHeight + 'px'
        }"></div>
    </div>
</template>

<script lang="ts" setup>
import langList from "@Lang/langList.ts"

// import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

import { useCurrentInstance } from "@Hooks/index.ts";
const proxy = useCurrentInstance().proxy;

import { onBeforeUnmount, ref, shallowRef, onMounted, provide, watch, nextTick, toRaw, inject } from 'vue'

const props = defineProps({
    mode: {
        type: String,
        default: "edit"
    },
    spacing: {
        type: Boolean,
        default: false
    },
    spacingHeight: {
        type: [String, Number],
        default: 32
    },
    label: {
        type: String,
        default: ""
    },
    required: {
        type: Boolean,
        default: false
    },
    placeholder: {
        type: String,
        default: ""
    },
    readonly: {
        type: Boolean,
        default: false,
    },
    disabled: {
        type: Boolean,
        default: false,
    },
    tip: {
        type: String,
        default: ""
    },
    tipDetail: {
        type: String,
        default: ""
    },
    divider: {
        type: Boolean,
        default: false
    }
})

// 監聽當前模式，切換可用和不可用
watch(() => props.mode, (val) => {
    changeEditorEnable();
})

// 切換編輯器的可用和不可用狀態
function changeEditorEnable() {
    if (props.mode == "view") {
        disable();
    } else {
        enable();
    }
}

// 監聽只讀，切換可用還是不可用
watch(() => props.readonly, (val) => {
    if (props.readonly == true) {
        disable();
    } else {
        enable();
    }
})

// 監聽禁用，切換可用還是不可用
watch(() => props.disabled, (val) => {
    if (props.disabled == true) {
        disable();
    } else {
        enable();
    }
})

// 是否顯示編輯器
const showRichTextEditor = ref(true);

// 监听语言的切换
watch(() => proxy.$i18n.global.locale, (val) => {
    // 销毁原来的编辑器
    const editor = _editor.value
    if (editor == null) return
    editor.destroy()
    // 重新渲染編輯器
    showRichTextEditor.value = false;
    nextTick(() => {
        showRichTextEditor.value = true;
    })
})

// 各個語言的富文本内容
const richText = defineModel();

// 富文本内容空值填值
for (let item in richText.value) {
    if (!richText.value[item]) {
        richText.value[item] = "<p><br></p>";
    }
}

// 當前選擇的語言
const currentLang = ref(langList[0].value);

// 切換語言
function changeLang(lang: string) {
    // 記錄舊值
    let oldLang = toRaw(currentLang.value);
    let oldText = toRaw(richText.value[currentLang.value]);
    // 先清空當前富文本 (不使用clear会报错)
    clearRichText(() => {
        // 切換語言
        currentLang.value = lang;
        // 舊值賦值
        richText.value[oldLang] = oldText;
    })
}

// 工具欄配置
const toolbarConfig = {

}

// 編輯器配置
const editorConfig = ref({
    readOnly: props.readonly || props.disabled ? true : false,
    autoFocus: false,
    placeholder: props.placeholder,
    EXTEND_CONF: {
        mentionConfig: {
            showModal: function () { },
            hideModal: function () { },
        }
    }
});

// 编辑器实例，必须用 shallowRef
const _editor = shallowRef()

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = _editor.value
    if (editor == null) return
    editor.destroy()
})

// 當前是否是全屏
const isFullScreen = ref(false);

// 編輯器創建完成
const handleCreated = (editor: any) => {
    _editor.value = editor // 记录 editor 实例，重要！
    nextTick(() => {
        // 切換一次可用狀態
        changeEditorEnable();
    })
    // 監聽全屏事件
    editor.on('fullScreen', () => {
        isFullScreen.value = true;
    })
    editor.on('unFullScreen', () => {
        isFullScreen.value = false;
    })
}

/**
 * 清空
 */
function clear() {
    clearRichText(() => {
        // 清空全部内容
        for (let lang of langList) {
            richText.value[lang.value] = "<p><br></p>";
        }
        // 语言切换回第一个
        currentLang.value = langList[0].value;
    })
}

/**
 * 清空富文本组件
 * @param callback
 */
function clearRichText(callback: Function) {
    const editor = _editor.value;
    if (editor != null) {
        editor.clear();
    }
    nextTick(() => {
        callback && callback();
    })
}

/**
 * 开启可用
 */
function enable() {
    const editor = _editor.value;
    if (editor == null) return
    editor.enable();
}

/**
 * 开启禁用
 */
function disable() {
    const editor = _editor.value;
    if (editor == null) return
    editor.disable();
}

defineExpose({
    clear,
    enable,
    disable
})

</script>

<style scoped>
.mrc-ess-rich-text :deep(.w-e-text-container) {
    background-color: rgb(var(--v-theme-surface));
    color: rgb(var(--v-theme-text--black));
}

.mrc-ess-rich-text :deep(.w-e-bar-divider) {
    background-color: rgb(var(--v-theme-divider));
}

/* .mrc-ess-rich-text :deep(.w-e-bar-item svg) {
    fill: rgb(var(--v-theme-text--black));
}

.mrc-ess-rich-text :deep(.w-e-bar-item .disabled svg) {
    fill: var(--w-e-toolbar-disabled-color);
}

.mrc-ess-rich-text :deep(.w-e-bar-item button) {
    color: rgb(var(--v-theme-text--black));
}

.mrc-ess-rich-text :deep(.w-e-bar-item .disabled) {
    color: var(--w-e-toolbar-disabled-color);
} */

.mrc-ess-rich-text :deep(.w-e-text-container [data-slate-editor] p) {
    margin: 4px 0;
}

.mrc-ess-rich-text :deep(.w-e-text-container [data-slate-editor]) {
    font-size: 14px;
    padding-left: 0px;
    padding-right: 0px;
    word-break: break-all;
}

.mrc-ess-rich-text :deep(.w-e-bar) {
    background-color: transparent;
}

.mrc-ess-rich-text :deep(.w-e-scroll) {
    padding: 2px 12px;
}

.mrc-ess-rich-text {
    box-shadow: 0px 1px 2px 0px #0000000D;
}

.mrc-ess-rich-text :deep(.w-e-text-container h1) {
    font-size: 21px;
    font-weight: bold;
}

.mrc-ess-rich-text :deep(.w-e-text-container h2) {
    font-size: 21px;
    font-weight: bold;
}

.mrc-ess-rich-text :deep(.w-e-text-container h3) {
    font-size: 16px;
    font-weight: bold;
}

.mrc-ess-rich-text :deep(.w-e-text-container h4) {
    font-size: 14px;
    font-weight: bold;
}

.mrc-ess-rich-text :deep(.w-e-text-container h5) {
    font-size: 12px;
    font-weight: bold;
}

.mrc-ess-rich-text :deep(.w-e-text-container h6) {
    font-size: 12px;
}
</style>
